package com.nick.core.common;


import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.Serializable;

/***
 * 统一返回格式
 */
public class ApiResult<T> implements Serializable {

    private static final long serialVersionUID = -1392602542807277978L;
    private static final String SUCCESS = "success";
    private int status;
    private String error;
    @JSONField(serialzeFeatures = {SerializerFeature.WriteMapNullValue})
    private String message;
    @JSONField(serialzeFeatures = {SerializerFeature.WriteMapNullValue})
    private T payload;

    public ApiResult() {
    }

    private ApiResult(int status, String msg, T payload) {
        this.status = status;
        if (status == 200) {
            this.error = "";
            this.message = msg;
        } else {
            this.error = msg;
        }
        this.payload = payload;
    }

    public static ApiResult build(Throwable e) {
        int status = 500;
        if (e instanceof Exception) {
            status = 999;
        }
        return new ApiResult(status, e.getMessage(), null);
    }

    public static ApiResult success() {
        return new ApiResult(200, SUCCESS, null);
    }

    public static <T> ApiResult<T> build(T payload) {
        return new ApiResult(200, SUCCESS, payload);
    }

    public static ApiResult build(int status, String msg) {
        return new ApiResult(status, msg, null);
    }

    public static <T> ApiResult<T> build(int status, String msg, T payload) {
        return new ApiResult(status, msg, payload);
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getPayload() {
        return payload;
    }

    public void setPayload(T payload) {
        this.payload = payload;
    }

    @Override
    public String toString() {
        return this.toString();
    }
}
